<template>
  <s-layout>
    <view class="container">
      <view class="form-container">
        <!-- 头部标题 -->
        <view class="header-box">
          <text
            class="cicon-person-add"
            style="color: #0052d9; font-size: 44rpx; margin-right: 20rpx"
          ></text>
          <text class="title">{{ isEdit ? "编辑成员" : "新增成员" }}</text>
        </view>

        <!-- 基本信息区块 -->
        <view class="form-card">
          <fui-section
            title="成员信息"
            line-width="3px"
            line-color="#0052d9"
            isLine
            size="34"
          ></fui-section>

          <!-- 姓名 -->
          <fui-input
            label="姓名"
            placeholder="请输入用户姓名"
            v-model="formData.cu_name"
          >
            <text
              class="cicon-person"
              slot="prefix"
              style="color: #0052d9; font-size: 40rpx"
            ></text>
          </fui-input>

          <!-- 微信账号 -->
          <fui-input
            label="账号"
            placeholder="请输入账号"
            v-model="formData.wx_user"
          >
            <text
              class="cicon-wechat"
              slot="prefix"
              style="color: #0052d9; font-size: 40rpx"
            ></text>
          </fui-input>

          <!-- 微信密码 -->
          <fui-input
            label="密码"
            placeholder="请输入密码"
            v-model="formData.wx_pawd"
            :password="showPassword"
            :borderBottom="false"
          >
            <fui-icon
              :name="showPassword ? 'invisible' : 'visible'"
              color="#0052D9"
              :size="50"
              @click="showPassword = !showPassword"
            ></fui-icon>
          </fui-input>

          <!-- 职位 -->
          <fui-input
            label="职位"
            placeholder="请输入职位"
            v-model="formData.cu_job"
          >
            <text
              class="cicon-person-o"
              slot="prefix"
              style="color: #0052d9; font-size: 40rpx"
            ></text>
          </fui-input>

          <!-- 手机号 -->
          <fui-input
            label="手机号"
            placeholder="请输入手机号"
            v-model="formData.cu_phone"
          >
            <text
              class="cicon-phone"
              slot="prefix"
              style="color: #0052d9; font-size: 40rpx"
            ></text>
          </fui-input>

          <!-- 邮箱 -->
          <fui-input
            label="邮箱"
            placeholder="请输入邮箱"
            v-model="formData.cu_email"
          >
            <text
              class="cicon-email"
              slot="prefix"
              style="color: #0052d9; font-size: 40rpx"
            ></text>
          </fui-input>
        </view>
      </view>

      <!-- 提交按钮 -->
      <view class="submit-btn" @click="submit">
        <text class="btn-text">{{ isEdit ? "确认修改" : "确认添加" }}</text>
      </view>
    </view>
  </s-layout>
</template>

<script lang="ts" setup>
import { ref, reactive } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import sheep from "@/sheep";

interface PeopleListItem {
  company_id: string;
  createtime?: string;
  cu_avatarUrl: string;
  cu_email: string;
  cu_id: string;
  cu_job: string;
  cu_name: string;
  cu_phone: string;
  cu_role?: string;
  cu_status?: string;
  del_type?: string;
  updatetime?: string;
  user_id?: string;
  wx_id?: string;
  wx_pawd: string;
  wx_user: string;
}

interface SubmitData {
  company_id: string;
  cu_avatarUrl: string;
  cu_email: string;
  cu_id?: string;
  cu_job: string;
  cu_name: string;
  cu_phone: string;
  cu_role?: string;
  cu_status?: string;
  wx_pawd: string;
  wx_user: string;
  createtime?: string;
  del_type?: string;
  updatetime?: string;
  user_id?: string;
  wx_id?: string;
}

// --- Data ---
const companyId = ref<string | null>(null);
const isEdit = ref(false);

const formData = reactive({
  cu_name: "",
  cu_job: "",
  cu_phone: "",
  cu_email: "",
  wx_user: "",
  wx_pawd: "",
  company_id: "",
  cu_avatarUrl: "",
  cu_id: "",
  cu_role: "1",
  cu_status: "0",
  createtime: "",
  del_type: "0",
  updatetime: "",
  user_id: "",
  wx_id: "",
});

const showPassword = ref(true);

// --- Lifecycle Hooks ---
onLoad((options) => {
  if (options?.companyId) {
    companyId.value = options.companyId;
    formData.company_id = options.companyId;
  } else {
    console.error("Company ID not provided in options");
    uni.showToast({ title: "缺少必要参数", icon: "error" });
    setTimeout(() => uni.navigateBack(), 1500);
  }

  // 如果有 userData 参数，说明是编辑模式
  if (options?.userData) {
    try {
      const userData: PeopleListItem = JSON.parse(
        decodeURIComponent(options.userData)
      );
      isEdit.value = true;
      // 填充表单数据
      Object.assign(formData, userData);
    } catch (error) {
      console.error("解析用户数据失败:", error);
      uni.showToast({ title: "加载用户数据失败", icon: "none" });
    }
  }
});

// 表单验证方法
const validateForm = (): boolean => {
  // 验证姓名
  if (!formData.cu_name.trim()) {
    uni.showToast({ title: "请输入姓名", icon: "none" });
    return false;
  }

  // 验证账号
  if (!formData.wx_user.trim()) {
    uni.showToast({ title: "请输入账号", icon: "none" });
    return false;
  }

  // 验证密码
  if (!formData.wx_pawd) {
    uni.showToast({ title: "请输入密码", icon: "none" });
    return false;
  }

  // 验证职位
  if (!formData.cu_job.trim()) {
    uni.showToast({ title: "请输入职位", icon: "none" });
    return false;
  }

  // 验证手机号 (中国大陆手机号格式)
  if (!formData.cu_phone) {
    uni.showToast({ title: "请输入手机号", icon: "none" });
    return false;
  }

  const phoneRegex = /^1[3-9]\d{9}$/;
  if (!phoneRegex.test(formData.cu_phone)) {
    uni.showToast({ title: "请输入正确的手机号格式", icon: "none" });
    return false;
  }

  // 验证邮箱 (如果有填写)
  if (formData.cu_email) {
    const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
    if (!emailRegex.test(formData.cu_email)) {
      uni.showToast({ title: "请输入正确的邮箱格式", icon: "none" });
      return false;
    }
  }

  return true;
};

// --- Methods ---
const submit = () => {
  // 调用表单验证
  if (!validateForm()) {
    return;
  }

  const submitData: SubmitData = {
    company_id: companyId.value || "",
    cu_name: formData.cu_name,
    cu_job: formData.cu_job,
    cu_phone: formData.cu_phone,
    cu_email: formData.cu_email,
    wx_user: formData.wx_user,
    wx_pawd: formData.wx_pawd,
    cu_avatarUrl: formData.cu_avatarUrl,
    cu_role: formData.cu_role,
    cu_status: formData.cu_status,
    createtime: formData.createtime,
    del_type: formData.del_type,
    updatetime: formData.updatetime,
    user_id: formData.user_id,
    wx_id: formData.wx_id,
  };

  if (isEdit.value && formData.cu_id) {
    // 编辑模式
    submitData.cu_id = formData.cu_id;
    sheep.$api.qy_index
      .peopleaddupdate(submitData)
      .then((res) => {
        if (res.code === 200) {
          uni.showToast({ title: "修改成功", icon: "success" });
          setTimeout(() => {
            uni.navigateBack({
              delta: 1,
            });
          }, 1500);
        } else {
          uni.showToast({ title: res.msg || "修改失败", icon: "none" });
        }
      })
      .catch((error) => {
        console.error("修改用户失败:", error);
        uni.showToast({ title: "修改失败", icon: "none" });
      });
  } else {
    // 添加模式
    sheep.$api.qy_index
      .peopleaddupdate(submitData)
      .then((res) => {
        if (res.code === 200) {
          uni.showToast({ title: "添加成功", icon: "success" });
          setTimeout(() => {
            uni.navigateBack();
          }, 1500);
        } else {
          uni.showToast({ title: res.msg || "添加失败", icon: "none" });
        }
      })
      .catch((error) => {
        console.error("添加用户失败:", error);
        uni.showToast({ title: "添加失败", icon: "none" });
      });
  }
};
</script>

<style lang="scss" scoped>
@import "/src/sheep/scss/icon/_coloricon.scss";

.container {
  padding: 30rpx;
  background: #f8f9fa;
  min-height: 100vh;
  box-sizing: border-box;
}

.header-box {
  display: flex;
  align-items: center;
  padding: 30rpx 0;
  .title {
    font-size: 40rpx;
    font-weight: 700;
    color: #1a1a1a;
  }
}

.form-card {
  background: #fff;
  border-radius: 16rpx;
  padding: 20rpx 20rpx 0 20rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 82, 217, 0.1);

  ::v-deep .fui-input__wrap {
    padding-left: 0 !important;
    padding-right: 0 !important;
  }

  ::v-deep .fui-input__padding {
    padding: 26rpx 0 !important;
  }
}

.submit-btn {
  background: linear-gradient(
    135deg,
    #0052d9,
    #2979ff
  ); /* Gradient background */
  border-radius: 50rpx; /* Fully rounded */
  height: 90rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 8rpx 16rpx rgba(0, 82, 217, 0.3); /* Button shadow */
  transition: background 0.3s ease;

  &:active {
    background: linear-gradient(
      135deg,
      darken(#0052d9, 5%),
      /* Darken on press */ darken(#2979ff, 5%)
    );
  }

  .btn-text {
    color: #fff;
    font-size: 34rpx;
    font-weight: 500;
  }

  /* 新增：固定在底部 */
  position: fixed;
  bottom: 30rpx; /* 距离底部的距离 */
  left: 30rpx; /* 距离左侧的距离 */
  right: 30rpx; /* 距离右侧的距离 */
}
</style>
